package utils

import(
	"fmt"
	"net"
	"encoding/json"
	"encoding/binary"
	"project06/common/message"

)
type Transfer struct{
	Conn net.Conn
	Buf [8096]byte

}

func (this *Transfer)ReadPkg() (mes message.Message,err error){
	
	_,err=this.Conn.Read(this.Buf[:4])
	//fmt.Println("读取到的数据长度为：",rn)
	//fmt.Println("读取到的数据buf=：",buf)
	if err !=nil{
		fmt.Println("conn.Read(buf) err",err)
		return
	}
	var mesLen uint32
	mesLen=binary.BigEndian.Uint32(this.Buf[0:4])
	
	n,err:=this.Conn.Read(this.Buf[:mesLen])
	//fmt.Println("读取到的data数据长度为：",n)
	if n!=int(mesLen)||err !=nil{
		fmt.Println("conn.Read(mes) err",err)
		return
	}
	
	err=json.Unmarshal(this.Buf[:mesLen],&mes)
	if err!=nil{
		fmt.Println("反序列化mes失败，err",err)
		return
	}
	return
}


func (this *Transfer)WritePkg(data []byte)(err error){
	
	mesLen:=uint32(len(data))
	binary.BigEndian.PutUint32(this.Buf[0:4],mesLen)
	//发送mes的长度给服务器
	n,err:=this.Conn.Write(this.Buf[:4])
	if n!=4 || err!=nil{
		fmt.Println("conn.write(buf) err",err)
		return
	}

	n,err=this.Conn.Write(data)
	if n!=int(mesLen)||err!=nil{
		fmt.Println("conn.write(data) err",err)
		return
	}
	return
}